package webrtc

import (
	"encoding/json"
	"log"

	"github.com/gofiber/websocket/v2"
	"github.com/pion/webrtc/v3"
)

// web连接这个
func WebConn(c *websocket.Conn) *PeerConnectionState {
	newPeer := PeerConnectionState{
		PeerConnection: nil,
		Role:           Receiver,
		Websocket: &ThreadSafeWriter{
			Conn: c,
			Send: make(chan []byte),
		}}
	return &newPeer
}

func WebRTCConn(peer *PeerConnectionState, room *Room) error {
	var config webrtc.Configuration
	// if os.Getenv("ENVIRONMENT") == "PRODUCTION" {
	config = turnConfig
	// }
	peerConnection, err := webrtc.NewPeerConnection(config)
	if err != nil {
		log.Print(err)
		return err
	}
	// defer peerConnection.Close()

	for _, typ := range []webrtc.RTPCodecType{webrtc.RTPCodecTypeVideo, webrtc.RTPCodecTypeAudio} {
		if _, err := peerConnection.AddTransceiverFromKind(typ, webrtc.RTPTransceiverInit{
			Direction: webrtc.RTPTransceiverDirectionRecvonly,
		}); err != nil {
			log.Print(err)
			return err
		}
	}
	room.ListLock.Lock()
	room.Connections = append(room.Connections, peer)
	room.ListLock.Unlock()

	// log.Println(room.Connections)
	peer.PeerConnection = peerConnection
	peerConnection.OnICECandidate(func(i *webrtc.ICECandidate) {
		if i == nil {
			return
		}
		message, err := json.Marshal(SendMessage{
			Type: ICE,
			Data: i.ToJSON(),
		})
		if err != nil {
			log.Println(err)
			return
		}
		peer.Websocket.Send <- message
	})

	peerConnection.OnConnectionStateChange(func(pp webrtc.PeerConnectionState) {
		switch pp {
		case webrtc.PeerConnectionStateFailed:
			if err := peerConnection.Close(); err != nil {
				log.Print(err)
			}
		case webrtc.PeerConnectionStateClosed:
			peer.RTCStop()
		}
	})
	Peers[peer] = room
	room.SyncConnection()
	return nil
}
